//index.js
//获取应用实例
const app = getApp()
//var datajs = require('../../data/data.js');
Page({
  data: {
    selectArr: [],
    selectIndex: 1,
    area: [],
    yourTop: -1,
    yourNumber: '',
    noArr: [],
    history: [],
    colorArr:[60,150,220],
    antiColor: '', // 计算出来别填
    openid: '',
    adMinkey:'',
    key:"hzyjt666", //hzyjt666
    adminShow: false,
    color: '60,150,220' //239,51,66
  },
  changeColor(event){
    let value = event.detail.value
    let index = event.target.dataset.index
    if(value<=255){
      let color = this.data.color.split(',')
      let colorArr = this.data.colorArr
      color[index] = value
      colorArr[index] = value
      this.setData({
        color:color.toString(),
        colorArr:colorArr
      },()=>{
        this.setColor()
      })
    }
  },
  setColor(){
    this.getAntiColor()
    wx.setNavigationBarColor({//设置导航栏颜色
      frontColor: '#ffffff',
      backgroundColor: this.colorRGBtoHex(`rgb(${this.data.color})`)
    });
 },
  bindPickerChange: function (event) {
    let value = event.detail.value
    let selectArr = this.data.selectArr
    selectArr[value].percent = (selectArr[value].quantity*100/(selectArr[value].max - selectArr[value].min + 1 - selectArr[value].noPass)).toFixed(2)
    this.setData({
      selectIndex: value,
      selectArr: selectArr,
      noArr: [],
      area: [],
      yourTop: -1,
      yourNumber: '',
    })
  },
  numberInput(event) {
    this.setData({
      yourNumber: event.detail.value
    })
  },
  delete(){
    var that = this;
    wx.removeStorage({
      key: 'history',
      success: function(res) {
        that.setData({
          history:[]
        })
      },
    })
  },
  showDelete(){
    let _this = this;
     wx.showModal({
       title: '温馨提示',
       content: '确认清空历史记录吗？',
       cancelText: '我再想想',
       confirmColor: _this.colorRGBtoHex(`rgb(${this.data.color})`),
       confirmText: '清空',
       success(res) {
         if (res.confirm) {
          _this.delete()
         } 
       }
     })
  },
  cancelShow(){
    this.setData({
      adminShow: false,
    })
  },
  keyInput(event){
    this.setData({
      adMinkey: event.detail.value,
    })
  },
  checkKey(){
    var key = this.data.key
    if(this.data.adMinkey!=key) return wx.showToast({
      title: '密码错误',
      icon: 'none',
      duration: 2000
    })
    this.cancelShow()
    this.toAdmin()
  },
  toAdmin(){
    wx.navigateTo({
      url: '/page/admin/admin',
      });
  },
  showAdmin() {
    var _this =  this;
    var key = this.data.key
     wx.showModal({
       title: '温馨提示',
       content: '确认进入管理台吗？',
       cancelText: '取消',
       confirmColor: _this.colorRGBtoHex(`rgb(${this.data.color})`),
       confirmText: '进入',
       success(res) {
         if (res.confirm) {
            if(_this.data.adMinkey!=key) return  _this.setData({
              adminShow: true,
            })
            _this.toAdmin()
        }
      }
     })
  },
  randomNum(min, max, length, noLength, number) {
    var dValue = max - min;
    var allArr = [], arr = [];
    var active = -1;
    for(var i=0;i < dValue; i++){
      if(i+1 == number) continue;
      allArr.push(Number(i+1))
    }
    allArr.sort(function(){
      return 0.5 - Math.random();
    })
    allArr = allArr.slice(noLength,allArr.length)
    active = Math.round(allArr.length * Math.random())
    allArr.splice(active,0,Number(number))
    arr = allArr.slice(0, length)
    let history = this.data.history
    history.unshift({
      number: number,
      isInArr: active < length,
      top: active,
      value: this.data.selectArr[this.data.selectIndex].value
    })
    this.setData({
      area: arr,
      yourTop: active,
      history: history,
    }, () => {
      wx.setStorageSync('history', JSON.stringify(history))
      wx.hideLoading()
    })
  },
  startClick() {
    var selectItem = this.data.selectArr[this.data.selectIndex]
    var number = this.data.yourNumber
    if (!(/^[+]{0,1}(\d+)$/.test(number) && Number(number) >= selectItem.min && Number(number) <= selectItem.max)) {
      return wx.showToast({
        title: '号码不在范围内',
        icon: 'none',
        duration: 2000
      })
    }
    wx.showLoading({
      title: '生成摇号列表',
    })
    this.randomNum(selectItem.min, selectItem.max, selectItem.quantity,selectItem.noPass, number)
  },
  getAntiColor(){
    var color = this.data.color
    this.setData({
      antiColor:`${255-color.split(',')[0]},${255-color.split(',')[1]},${255-color.split(',')[2]}`
    })
  },
  colorRGBtoHex(color) {
    var rgb = color.split(',');
    var r = parseInt(rgb[0].split('(')[1]);
    var g = parseInt(rgb[1]);
    var b = parseInt(rgb[2].split(')')[0]);
    var hex = "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
    return hex;
 },
 getData(){
  wx.showLoading({
    title: '',
  })
  const db = wx.cloud.database()
  // 查询当前用户所有的 counters
  db.collection('selectArr').where({
    //_openid: this.data.openid
  }).get({
    success: res => {
      this.setData({
        selectArr: res.data&&res.data.length>0? res.data.reverse() : [{
          max:100,
          min:1,
          noPass:50,
          quantity:20,
          title:'暂无数据',
          value:'NODATA'
        }]
      },()=>{
        this.bindPickerChange({detail:{value:0}})
        wx.hideLoading()
      })
    },
    fail: err => {
      wx.showToast({
        icon: 'none',
        title: '查询记录失败'
      })
      this.setData({
        selectArr: [{
          max:100,
          min:1,
          noPass:50,
          quantity:20,
          title:'暂无数据',
          value:'NODATA'
        }]
      },()=>{
        this.bindPickerChange({detail:{value:0}})
        wx.hideLoading()
      })
    }
  })
 },
  //事件处理函数
  onLoad: function () {
    var that = this;
    if (app.globalData.openid) { // 获取openid 
      this.setData({
        openid: app.globalData.openid
      })
    }
    wx.getStorage({ // 读取历史记录
      key: 'history',
      success: function (res) {
        that.setData({
          history: JSON.parse(res.data || []),
        })
      },
      error: function () {
        that.setData({
          history: [],
        })
      }
    })
    this.setColor()
  },

  onShow: function (){
    this.getData()
  }
})